<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/12/26
 * Time: 下午5:31
 */

namespace App\Http\Controllers;

use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\Token\Facades\Token;

class OAuth2 extends Controller
{
    protected $sessionKey = '__OPERATOR_OPEN_ID__';

    protected $sessionTargetUrlKey = '__OAUTH_TARGET_URL__';

    public function index(Request $request)
    {
        $callbackUrl = $request->input('callback');
        $config          = config('wechat');
        $token           = $request->input('token');
        if (!Token::has($token)) {
            throw new \Exception('帐号过期，请退出后重新登录');
        }
        $uid         = Token::data('id');
        $user        = User::find($uid);

        $config['oauth'] = [
            'scopes'   => ['snsapi_base'],
            'callback' => route('oauth_callback'),
        ];

        // 未登录
        $userInfo = session($this->sessionKey);
        $open_id  = array_get($userInfo, 'open_id');
        if (!$open_id) {
            session([
                $this->sessionTargetUrlKey => $callbackUrl,
            ]);

            $app   = Factory::officialAccount($config);
            $oauth = $app->oauth;
            Log::info(  '要跳转了，回调地址：' . $callbackUrl);
            return $oauth->redirect();
        } else {
            $user->open_id = $open_id;
            $user->save();
            $targetUrl = $callbackUrl ? : session($this->sessionTargetUrlKey);
            if ($targetUrl) {
                $targetUrl = addQueryParam($targetUrl, 'open_id', $open_id);
                return redirect()->to($targetUrl);
            }
            echo $open_id;
        }

    }

    public function oauthCallback()
    {
        $app   = Factory::officialAccount(config('wechat'));

        // 获取 OAuth 授权结果用户信息
        $user = $app->oauth->user();

        session([
            $this->sessionKey => [
                'open_id' => $user->getId(),
            ]
        ]);

        $targetUrl = session($this->sessionTargetUrlKey) ?:  route('oauth_index');
        $targetUrl = addQueryParam($targetUrl, 'open_id', $user->getId());

        return redirect()->to($targetUrl);
    }
}